package com.example.xyxwebbackend001.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.xyxwebbackend001.model.DTO.ArticleDTO;
import com.example.xyxwebbackend001.model.DTO.ArticleSimpleDTO;
import com.example.xyxwebbackend001.model.entity.Article;
import com.example.xyxwebbackend001.model.vo.ArticleListVO;
import com.example.xyxwebbackend001.model.vo.ArticlePathListVO;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

@Mapper
public interface ArticleMapper extends BaseMapper<Article> {
    @Select("SELECT a.art_id AS id, a.title, a.summary, ai.image_path AS coverImage, a.tags " +
            "FROM article a " +
            "LEFT JOIN article_image ai ON a.art_id = ai.art_id AND ai.image_type = 'cover' " +
            "WHERE a.city_id = #{cityId} AND a.status = 0 " +
            "ORDER BY a.create_time DESC")
    List<ArticleSimpleDTO> selectArticlesByCityId(String cityId);

    @Select("SELECT * FROM article WHERE art_id = #{articleId}")
    ArticleDTO selectArticleById(Integer articleId);

    @Select("SELECT a.art_id AS artId, a.title, a.author, a.summary, a.status," +
            "c.city_name AS cityName, " +
            "DATE_FORMAT(a.create_time, '%Y-%m-%d %H:%i:%s') AS createTime " +
            "FROM article a " +
            "LEFT JOIN city c ON a.city_id = c.city_id " +
            "WHERE (#{keyword} IS NULL OR #{keyword} = '' OR a.title LIKE CONCAT('%', #{keyword}, '%')) " +
            "AND a.status != 2")
    List<ArticleListVO> selectArticleByKeyword(String keyword);

    @Update("UPDATE article SET status = #{status} WHERE art_id = #{articleId}")
    int updateArticleStatus(@Param("articleId") Integer articleId, @Param("status") Integer status);

    @Update("UPDATE article SET view_counts = view_counts + 1 WHERE art_id = #{articleId}")
    void incrementViewCount(Integer articleId);

    @Select("<script>" +
            "SELECT art_id AS id, title, summary, " +
            "(SELECT image_path FROM article_image WHERE art_id = a.art_id AND image_type = 'cover' LIMIT 1) AS coverImage, " +
            "tags " +
            "FROM article a " +
            "WHERE a.status = 0 " +
            "ORDER BY " +
            "<choose>" +
            "  <when test='sort != null'>${sort}</when>" +
            "  <otherwise>view_counts DESC</otherwise>" +
            "</choose>" +
            "</script>")
    List<ArticleSimpleDTO> getSortedArticles(@Param("sort") String sort);



    @Select("SELECT title, CONCAT('/cultPop/', art_id) AS path " +
            "FROM article " +
            "WHERE status = 0 " +
            "AND FIND_IN_SET(#{tags}, tags) > 0")
    List<ArticlePathListVO> getArticlePathList(@Param("tags") String tags);
}
